package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.db.pojo.DeptEntiy;
import com.example.his.api.mis.controller.form.dept.DeleteDeptByIdsForm;
import com.example.his.api.mis.controller.form.dept.InsertDeptForm;
import com.example.his.api.mis.controller.form.dept.SearchDeptByPageForm;
import com.example.his.api.mis.controller.form.dept.UpdateDeptForm;
import com.example.his.api.mis.service.DeptService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController("MisDeptController")
@RequestMapping("/mis/dept")
public class DeptController {
  @Resource
  private DeptService deptService;
  
  @GetMapping("/searchAllDept")
  public R searchAllDept() {
    ArrayList <HashMap> list = deptService.searchAllDept();
    return R.ok().put("list", list);
  }
  
  @PostMapping("/insert")
  @SaCheckPermission(value = { "ROOT", "DEPT:INSERT" }, mode = SaMode.OR)
  public R insert(@RequestBody @Valid InsertDeptForm form) {
    Map <String, Object> param = BeanUtil.beanToMap(form);
    Integer id = deptService.insert(param);
    return R.ok().put("result", id);
  }
  
  @PostMapping("/deleteByIds")
  @SaCheckPermission(value = { "ROOT", "DEPT:DELETE" }, mode = SaMode.OR)
  public R deleteByIds(@RequestBody @Valid DeleteDeptByIdsForm form) {
    int count = deptService.deleteByIds(form.getIds());
    return R.ok().put("result", count);
  }
  
  @PostMapping("/update")
  @SaCheckPermission(value = { "ROOT", "DEPT:UPDATE" }, mode = SaMode.OR)
  public R update(@RequestBody @Valid UpdateDeptForm form) {
    boolean b = deptService.update(BeanUtil.beanToMap(form));
    return R.ok().put("result", b);
  }
  
  @GetMapping("/searchById/{id}")
  @SaCheckPermission(value = { "ROOT", "DEPT:SELECT" }, mode = SaMode.OR)
  public R searchById(@PathVariable("id") Integer id) {
    DeptEntiy map = deptService.searchById(id);
    return R.ok().put("result", map);
  }
  
  @PostMapping("/searchByPage")
  @SaCheckPermission(value = { "ROOT", "DEPT:SELECT" }, mode = SaMode.OR)
  public R searchByPage(@RequestBody SearchDeptByPageForm form) {
    Integer page = form.getPage();
    Integer length = form.getLength();
    int start = (page - 1) * length;
    Map param = BeanUtil.beanToMap(form);
    param.put("start", start);
    PageUtils pageUtils = deptService.searchByPage(param);
    return R.ok().put("result", pageUtils);
  }
  
}
  
